# -*- coding:utf8 -*-
import pandas as pd
import requests,os
import json,time,re
import ischinese

APIKEY="BWN9pwIZx6aoSjhSeGEiFikd"
secret_key="1cNeE3iG2czhcRtjsLrEuOul100bxKNI"
#APIKEY="fVkmSOXCgorPfvJ8Kl0ZKnIq"
#secret_key="pOReWqziKfQXXMJ4WJDwbvwjnKtm6LKj"

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKEY+"&client_secret="+secret_key
    print(url)   
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main(contents,token):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + token
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content":'''Please provide a one sentence description of the content based on the following text. Require no more than 30 words. The main text is:\n%s.'''%(contents)
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, timeout=120, headers=headers, data=payload)
    except requests.exceptions.RequestException:
        return False
    result = json.loads(response.text)
    if 'result' not in result: return None
    return result['result']

if __name__ == '__main__':
    tmps  = [ candidate.split('\t')[0] for candidate in open("tmp1.txt","r") ]
    token = get_access_token()
    for tmp in os.walk("../recipes"):
        for tfile in tmp[2]: 
            if tfile.split(".")[0].isdigit() == False: continue
            i = int(tfile.split('.')[0])
            if str(i)  in tmps: continue
            test_file = "../recipes/%d.md"%(i)
            if os.path.exists(test_file) == False: continue
            data = open(test_file,"r").read().strip()
            print(test_file,data)
            cate = main(data,token)
            while cate is None or (cate.startswith('Please refer to relevant websites for more information') and 'Please refer to relevant websites for more information' not in data) or ischinese.judge(cate):
                cate = main(open(test_file,"r").read().strip(),token)
            if '\n' in cate: cate = cate.split("\n")[0]
            print(i,cate)
            with open('tmp1.txt','a') as f: f.write("%d\t%s\n"%(i,cate))
